--- 常量和方法等的module, 在初始化时加载
extrauth_cons = {}

extrauth_cons.salt = "its a very secret string"
extrauth_cons.divider = ":"
extrauth_cons.divider1 = "|"
extrauth_cons.login_timeout = 360000

extrauth_cons.db_options = {
    host = "127.0.0.1",
    port = 3306,
    database = "test",
    user = "root",
    password = "",
    charset = "utf8",
    max_packet_size = 1024 * 1024,
}

function extrauth_cons.split(s, delim) --按一个字符delim分隔字符串s
    local start = 1
    local t = {}
    while true do
        local pos = string.find(s, delim, start, true) -- plain find
        if not pos then
            break
        end
        table.insert(t, string.sub(s, start, pos - 1))
        start = pos + 1
    end
    table.insert(t, string.sub(s, start))
    return t
end

-- 认证用cookie长这样: 名为 extrauth_{auth_group}_token,
-- 内容为 base64(sha1(salt,basic_text)):basic_text  basic_text为 user_id:admin:groups:timeout_time
-- return 0ok 1未登录或过期 2无权限
function extrauth_cons.authenticate(cookie, need_admin, auth_group)
    if cookie ~= nil and cookie:find(extrauth_cons.divider) ~= nil then
        -- If there's a cookie, split off the HMAC signature and basic_text.
        local divider = cookie:find(extrauth_cons.divider)
        local basic_text = cookie:sub(divider + 1)
        local hmac = cookie:sub(0, divider - 1)

        -- Verify that the signature is valid.
        if ngx.encode_base64(ngx.hmac_sha1(extrauth_cons.salt, basic_text)) == hmac then
            local table = extrauth_cons.split(basic_text, extrauth_cons.divider)

            -- Verify expire time
            if table[4] and tonumber(table[4]) >= os.time() then

                -- Verify |group|
                if table[3] and table[3]:find(extrauth_cons.divider1 .. auth_group .. extrauth_cons.divider1) then
                    return 0;
                else
                    return 2;
                end
            else
                return 1 -- expire
            end
        else
            return 3 -- token format error
        end
    else
        return 1 -- no cookie
    end
end

extrauth_cons.sql_select_user = [[SELECT * FROM `extrauth_user`
     WHERE `user_name` = %s AND `passwd` = '%s' AND `is_deleted` = 0;]]

-- extrauth_cons.db

return extrauth_cons
